package se.zens.demo.wsapp.implementation.exchangerates;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import se.zens.demo.wsapp.configuration.WSAppConfiguration;
import se.zens.demo.wsapp.implementation.AbstractWSAppProcessor;
import se.zens.demo.wsapp.implementation.exceptions.InvalidCurrencyException;
import se.zens.demo.wsapp.implementation.exceptions.InvalidExchangeRateException;
import se.zens.demo.wsapp.interfaces.WSAppResultCodes;
import se.zens.demo.wsapp.interfaces.model.AddExchangeRateRequest;
import se.zens.demo.wsapp.interfaces.model.AddExchangeRateRessponse;
import se.zens.demo.wsapp.interfaces.model.ExchangeRate;

/**
 * Add or update new rate
 */
public class AddExchangeRateProcessor extends
		AbstractWSAppProcessor<AddExchangeRateRessponse>
{
	private static Logger logger = LogManager
			.getLogger(AddExchangeRateProcessor.class);
	private AddExchangeRateRequest request;
	private AddExchangeRateRessponse response;
	private Map<String, ExchangeRate> currentExchangeRates;

	public AddExchangeRateProcessor(WSAppConfiguration config,
			AddExchangeRateRequest request,
			Map<String, ExchangeRate> currentExchangeRates)
	{
		this.request = request;
		this.currentExchangeRates = currentExchangeRates;
		this.response = new AddExchangeRateRessponse(request);

	}

	public void process()
	{
		try
		{
			validateExchangeRate(request.getNewRate());
			if (currentExchangeRates == null)
			{
				currentExchangeRates = new HashMap<String, ExchangeRate>();
			}
			if (currentExchangeRates.isEmpty())
			{
				logger.debug("Adding " + request.getNewRate());
			} else
			{
				logger.debug("Updating " + request.getNewRate());
			}
			currentExchangeRates.put(getCurrencyPairKey(request.getNewRate()),
					request.getNewRate());

			logger.debug("Done");

			response.setResultCode(WSAppResultCodes.SUCCESS);
			response.setResultMessage("SUCCESS");

		} catch (InvalidCurrencyException ex)
		{
			this.response.setResultCode(WSAppResultCodes.INVALID_CURRENCY);
			this.response.setResultMessage(ex.getMessage());
		} catch (InvalidExchangeRateException ex)
		{
			this.response.setResultCode(WSAppResultCodes.INVALID_EXCHANGERATE);
			this.response.setResultMessage(ex.getMessage());
		}
	}

	public AddExchangeRateRessponse getResponse()
	{
		return response;
	}

}
